import UIView from "../../../core/mvcFrame/view/UIView";
import GameListItem from "./GameListItem";

const {ccclass, property} = cc._decorator;
/*
*ClassName:PanelGameList
*Description:TODO
*Date:2019/10/30 21:52
*/
@ccclass
export default class PanelGameList extends UIView {

    protected static prefabUrl = "prefabs/panels/gameList/PanelGameList";
    protected static className = "PanelGameList";

    onLoad() {

    }

    @property(cc.ScrollView) scrollView: cc.ScrollView = null
    @property(cc.Prefab) itemPrefab: cc.Prefab = null
    @property(cc.Button) startBtn: cc.Button = null
    @property(cc.EditBox) editBox: cc.EditBox = null

    needItem: number = 0
    index: number = 0
    viewRect: cc.Rect = null
    needCulling = false
    // onLoad () {}

    start() {
        this.startBtn.node.on('click', () => {
            this.needItem +=  parseInt(this.editBox.string)
        })
        let pos = this.scrollView.node.parent.convertToNodeSpaceAR(
            this.scrollView.node.position
        )
        // 构造碰撞盒子 需要有预留
        this.viewRect = cc.rect(pos.x - 125, pos.y - 125, this.scrollView.node.width + 250, this.scrollView.node.height + 300 )
        this.scrollView.node.on('scroll-began', () => {
            this.needCulling = true
            console.log('scroll-began')
        })
        this.scrollView.node.on('scroll-ended', () => {
            this.culling()
            this.needCulling = false
            console.log('scroll-ended')
        })
        this.scrollView.node.on(cc.Node.EventType.TOUCH_CANCEL, () => {
            this.culling()
            // this.needCulling = false
            console.log('TOUCH_CANCEL')
        })
    }

    frameCreator =(dt: number)=> {
        if (this.needItem < 1) {
            return
        } else if(this.needItem === 1) {
            this.culling()
        }
        this.needItem--
        this.index++
        let itemNode = cc.instantiate(this.itemPrefab)
        let gameListItem :GameListItem = itemNode.getComponent(GameListItem);
        gameListItem.init(this.index);
        itemNode.color = cc.color(~~(Math.random() * 255), ~~(Math.random() * 255), ~~(Math.random() * 255))
        this.scrollView.content.addChild(itemNode)
    }

    culling() {
        this.scrollView.content.children.forEach((node) => {
            if(this.viewRect.containsRect(node.getBoundingBoxToWorld())){
                node.getComponent(GameListItem).itemShow()
            } else {
                node.getComponent(GameListItem).itemHide()
            }
        })
    }

    update(dt) {
        this.frameCreator(dt)
        if (this.needCulling) {
            console.log('is culling')
            this.culling()
        }
    }
}